﻿# -*- coding: utf-8 -*-

import os

DB_DEFAULT_FILENAME = "DEFAULT.DB"
DB_DEFAULT_DIRNAME = "DB"

class mdb():

    def __init__(self, file=None):
        if not file:
            self.db_filename = os.path.abspath(path.join(DB_DEFAULT_DIRNAME, DB_DEFAULT_FILENAME))
            if not os.path.exists(self.db_filename):
                os.makedis(DB_DEFAULT_DIRNAME)

        elif os.path.exists(file):
            if os.path.isfile(file):
               self.db_filename = os.path.abspath(file)
            elif path.isdir(file):
                self.db_filename = os.path.abspath(os.path.join(file, DB_DEFAULT_FILENAME))
        
        else:
            print(u"Error! Нет такой директории!")

        self._load()
        print "SIZE:", str(len(self.db_mem))


    def create(self, fio=None, phone=None, addr=None):
        if not fio or not phone:
            return []

        FIO, PHONE, ADDR = "", "", ""
        FIO = unicode(fio.lower())
        PHONE = unicode(phone)
        if addr: ADDR = unicode(addr)
        
        check = self.read(fio, phone)
        if len(check)>0:
            return check

        new_rec = [PHONE, FIO, ADDR]
        self.db_mem.append(new_rec)
        return new_rec


    def read(self, fio=None, phone=None):
        """ Получаем запись из базы. Используется fio AND phone. """
        if not fio and not phone:
            return []

        FIO, PHONE = "", ""
        if fio: FIO = unicode(fio.lower())
        if phone: PHONE = unicode(phone)

        res = []
        for record in self.db_mem:
            if (FIO in record[1].lower()) and (PHONE in record[0]):
                res.append(record)
        return res


    def update(self, fio=None, phone=None):
        pass


    def delete(self, fio=None, phone=None):
        db_mem = self.db_mem
        db_del = []
        for record in db_mem:
            if (not fio or fio in record) and (not phone or phone in record):
                db_del.append( db_mem.pop(record) )


    def _load(self):
        db_open = open(self.db_filename, "r")
        db_mem = []
        for line in db_open:
            split = line.decode("utf-8").split(";")
            if len(split) > 1:
                db_mem.append( split )
        self.db_mem = db_mem
        db_open.close()


    def _save(self):
        #db_open = open(self.db_filename, "w")
        db_open = open("save.db", "w")
        db_mem = self.db_mem
        for record in db_mem:
            line = ";".join(record)
            db_open.write(line+"\n")
        db_open.close()


    def count(self):
        return len(self.db_mem)
